package com.resttest.ljs.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Component
public class RabbitReceiver {

    @Autowired
    private Environment environment;
    @Autowired
    private RestTemplate restTemplate;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue,exchange = @Exchange(MqKeyConstant.exchangeName),key = MqKeyConstant.ceshi)
    }
    )
    public String receiver(Message message){
        try {
            if(message == null || message.getBody() == null){
                throw new Exception("队列消息为null");
            }
            String receive = new String(message.getBody(), StandardCharsets.UTF_8);//业务报文
            String url = "http://localhost:"+environment.getProperty("server.port")+MqKeyConstant.E.CESHI.getUrl();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            return restTemplate.postForObject(url,new HttpEntity<>(receive,headers),String.class);
        }catch (Exception e){
            return e.getMessage();
        }
    }
}
